import router from '@/router'
import store from '@/store'

// 白名单
const whiteList = ['/login']

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  // 用户已登录
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.hasUserInfo) {
        const { permission } = await store.dispatch('user/getUserInfo')
        // 处理用户权限，筛选出需要添加的路由
        const fileterRoutes = await store.dispatch('premission/fileterRoutes', permission.menus)
        // 循环添加对应动态路由
        fileterRoutes.forEach(item => {
          router.addRoute(item)
        })
        // 主动跳转
        return next(to.path)
      }
      next()
    }
  // 用户未登录
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
})
